<template>
  <div class="search-container">
    <!-- 顶部导航 -->
    <van-nav-bar left-arrow @click-left="$router.back()" title="搜索中心" />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <van-cell-group >
      <van-cell 
      v-for="(item,index) in showList"
      :key='index'
      icon="search" 
      @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})"
      >
      <template #title>
        <span class="custom-title" v-html="item"></span>  
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      suggestionList:[],
      timeID:null,
    }
  },
  methods: {
    onSearch () {
        this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    onInput () {
        clearTimeout(this.timeID)
        this.timeID = setTimeout(async ()=>{
            console.log(this.value);
            if(this.value ==''){
                this.suggestionList=[]
                return
            }
            let res = await getSuggestion(this.value)
                console.log(res);
            this.suggestionList = res.data.data.options
        },500)
    }
  },
  computed:{
      showList(){
          return this.suggestionList.map(value=>{
              let reg = new RegExp(this.value,'ig')
              return value.replace(
                  reg,
                  match =>`<span style="color:red">${match}</span>`
              )
          })
      }
  }
}
</script>

<style lang="less">
.search-container {
  .van-nav-bar__content {
    background-color: #009afb;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
  }
}
</style>
